import pymongo
from urllib import parse

def getmongo(username, password, database, host, port):
    # 对用户名和密码进行编码
    encoded_username = parse.quote_plus(username)
    encoded_password = parse.quote_plus(password)
    # 构建 MongoDB 连接字符串
    connection_string = f'mongodb://{encoded_username}:{encoded_password}@{host}:{port}/{database}'
    try:
        # 创建 MongoDB 客户端连接
        client = pymongo.MongoClient(connection_string)
        return client
    except Exception as e:
        print(f"连接 MongoDB 时出现错误: {e}")
        return None

# 实例化参数
username = 'admin'
password = '123456'
database = "admin"
host = "39.107.248.141"
port = "27017"

# 调用函数获取 MongoDB 客户端
mongo1 = getmongo(username, password, database, host, port)


